{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# add path\n",
    "import sys\n",
    "\n",
    "sys.path.append('..')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/data/tianyang/anaconda3/envs/reasoners/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "with open(\"/data/tianyang/llm-reasoners/logs/guided_decoding_gsm8k_BeamSearch/07312023-102305/algo_output/1.pkl\", \"rb\") as f:\n",
    "    bs_result = pickle.load(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# if you return the whole beam, just pick up random one to visualize\n",
    "bsr = bs_result[1]\n",
    "\n",
    "terminal_node = bsr.terminal_node\n",
    "tree = bsr.tree"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Visualizer URL: https://www.llm-reasoners.net/visualizer/09ee7052-7a0a-40c0-a4a3-d8ba814eddb9?accessKey=709aeec2\n"
     ]
    }
   ],
   "source": [
    "from reasoners.visualization import visualize\n",
    "from reasoners.algorithm.beam_search import BeamSearchNode\n",
    "\n",
    "def gsm8k_node_factory(n: BeamSearchNode):\n",
    "    if not n.state:\n",
    "        return {}\n",
    "\n",
    "    return {\n",
    "            \"action\": n.state[-1].action, \n",
    "            \"action_prob\": n.state[-1].action_prob ** (1 / n.state[-1].action_length), \n",
    "            \"action_confidence\": n.state[-1].action_confidence\n",
    "    }\n",
    "\n",
    "def gsm8k_edge_factory(n: BeamSearchNode):\n",
    "    if not n.state:\n",
    "        return {}\n",
    "\n",
    "    return {\n",
    "        \"reward\": n.reward\n",
    "    }\n",
    "\n",
    "visualize(bsr, node_data_factory=gsm8k_node_factory, edge_data_factory=gsm8k_edge_factory)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "reasoners",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
